package cn.edu.zut.salarymanagesystem.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;

import java.io.IOException;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.bean.vo.LoginResult;
import cn.edu.zut.salarymanagesystem.config.Storage;
import cn.edu.zut.salarymanagesystem.utils.Browser;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class LoginActivity extends AppCompatActivity {
    EditText id;//创建账号
    EditText passwd;//创建密码
    Button login;
    public static final int LOGIN_SUCCESS = 200;
    public static final int LOGIN_FAULT = 500;
    public static final int PASS_ERROR = 403;
    public static final int USER_NO_EXIT = 404;
    public static final int USER_LOCKED = 405;
    public static final int USER_LOGON = 201;
    public static final int NET_DISCONNECT = 501;
    public static final int TIMEOUT = 502;
    Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_SUCCESS:
                    LoginActivity.this.finish();
                    Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
                    break;
                case PASS_ERROR:
                    Toast.makeText(getApplicationContext(), "密码错误!", Toast.LENGTH_SHORT).show();
                    break;
                case USER_NO_EXIT:
                    Toast.makeText(getApplicationContext(), "账号不存在！", Toast.LENGTH_SHORT).show();
                    break;
                case USER_LOCKED:
                    Toast.makeText(getApplicationContext(), "账号被锁定！", Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_FAULT:
                    Toast.makeText(getApplicationContext(), "账号或密码为空！", Toast.LENGTH_SHORT).show();
                    break;
                case NET_DISCONNECT:
                    Toast.makeText(getApplicationContext(), "网络连接失败！", Toast.LENGTH_SHORT).show();
                    break;
                case TIMEOUT:
                    Toast.makeText(getApplicationContext(), "网络连接超时！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        id = findViewById(R.id.ed_id);
        passwd = findViewById(R.id.ed_psw);
        login = findViewById(R.id.login);
        login.setOnClickListener(v -> {
            //登录逻辑
            LoginOperate();
        });

    }

    public void LoginOperate() {
        //创建两个String类,储存从输入文本获取到的内容
        String user = id.getText().toString().trim();
        String pwd = passwd.getText().toString().trim();
        OkHttpClient client = Browser.getClient();
        //创建登录请求
        RequestBody requestBody = new FormBody.Builder().add("uid", user).add("password", pwd).build();
        Request requestLogin = new Request.Builder().url(Storage.url + "/login/auth").post(requestBody).build();
        client.newCall(requestLogin).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(TIMEOUT);
                e.printStackTrace();
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LoginResult result = JSON.parseObject(response.body().string(), LoginResult.class);
                if (result.getMessageCode() == LoginResult.LOGIN_SUCCESS) {
                    Storage.currentUser = result;
                    SharedPreferences.Editor sp = LoginActivity.this.getSharedPreferences("COOKIE", Context.MODE_PRIVATE).edit();
                    sp.remove("currentUser");
                    sp.putString("currentUser", JSON.toJSONString(result));
                    sp.apply();
                    Intent intent = new Intent(LoginActivity.this, FragmentActivity.class);
                    startActivity(intent);
                    handler.sendEmptyMessage(LOGIN_SUCCESS);
                } else if (result.getMessageCode() == LoginResult.PASS_ERROR) {
                    //登录
                    handler.sendEmptyMessage(PASS_ERROR);
                } else if (result.getMessageCode() == LoginResult.USER_NO_EXIT) {
                    handler.sendEmptyMessage(USER_NO_EXIT);
                } else {
                    handler.sendEmptyMessage(LOGIN_FAULT);
                }
            }
        });
    }
}
